from fastapi import HTTPException, Body
from pydantic import BaseModel, Field
from ..dependencies import success, router
from ..models.sys import Area
from math import floor

## 发送短信
@router.post('/sms', tags=['sys'])
async def send(mobile: str = Body(default='', embed=True)):
    list = [row for row in Area.select().order_by(Area.id).paginate(page, size).dicts()]
    return success()

@router.get('/area', tags=['sys'])
async def index(page: int = 1, size: int = 10):
    list = [row for row in Area.select().order_by(Area.id).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Area.select().count()
    })

@router.get('/area/tree', tags=['sys'])
async def tree():
    list = [{}, {}, {}]
    for row in Area.select().dicts():
        if row['id'] % 10000 == 0:
            list[0][row['id']] = row['name']
        elif row['id'] % 100 == 0:
            pid = floor(row['id'] / 10000) * 10000
            if(pid in list[1]):
                list[1][pid][row['id']] = row['name']
            else:
               list[1][pid] = {}
        else:
            pid = floor(row['id'] / 100) * 100
            if(pid in list[2]):
                list[2][pid][row['id']] = row['name']
            else:
               list[2][pid] = {}

    return success(list)

@router.put('/area/{id}', tags=['sys'])
async def update(id: int, params):
    Area.update(params).where(Area.id == id).execute()
    return success()
